<script setup>
import 'leaflet/dist/leaflet.css'
import '@supermap/iclient-leaflet/css/index'

import iServerConfigUrl from '/iServerConfig.json?url'

import { ElMessage } from 'element-plus'
import $ from 'jquery'
import axios from 'axios'

import L from 'leaflet'
import '@supermap/iclient-leaflet'
import 'proj4leaflet'

import { inject } from 'vue'
</script>

<template></template>

<script>
export default {
    name: 'BurstAnalyst',
    data() {
        return {
            restMapUrl: undefined,
            networkAnalystUrl: undefined,
            restDataUrl: undefined,
            map: undefined,
            sourceNodeIDs: [1, 10, 20, 29, 30, 40, 51, 53, 55, 57, 66, 79],
            burstPoint: undefined,
            burstPipeline: undefined,
            criticalPoints: []
        }
    },
    mounted() {
        this.map = inject('map');

        axios.get(iServerConfigUrl).then(res => {
            var iServerConfig = res.data;
            this.restMapUrl = `${iServerConfig.urls.BurstAnalyst.protocol}://${iServerConfig.urls.BurstAnalyst.hostname}:${iServerConfig.urls.BurstAnalyst.port}/${iServerConfig.urls.BurstAnalyst.restMapUrl}`;
            this.networkAnalystUrl = `${iServerConfig.urls.BurstAnalyst.protocol}://${iServerConfig.urls.BurstAnalyst.hostname}:${iServerConfig.urls.BurstAnalyst.port}/${iServerConfig.urls.BurstAnalyst.networkAnalystUrl}`;
            this.restDataUrl = `${iServerConfig.urls.BurstAnalyst.protocol}://${iServerConfig.urls.BurstAnalyst.hostname}:${iServerConfig.urls.BurstAnalyst.port}/${iServerConfig.urls.BurstAnalyst.restDataUrl}`;

            // 还原 map 显示范围
            if (this.map._size.x !== document.body.clientWidth) {
                $("#map")[0].style.width = '';
                this.map._size.x = document.body.clientWidth;
            }

            this.map.options.crs = new L.supermap.CRS.NonEarthCRS({
                bounds: L.bounds([-207.16, 63.44], [646.38, 498.37]),
                origin: L.point(-207.16, 498.37)
            });
            this.map.options.minZoom = 2;
            this.map.flyTo([280.91, 219.61], 2);

            // 添加底图
            new L.supermap.tiledMapLayer(this.restMapUrl).addTo(this.map);

            // 加载设施阀门
            var sqlParam = new L.supermap.GetFeaturesBySQLParameters({
                queryParameter: {
                    name: `burstdata_Network_Node@burstdata`,
                    attributeFilter: `SmID in ('${this.sourceNodeIDs.join('\',\'')}')`
                },
                toIndex: -1,
                maxFeatures: this.sourceNodeIDs.length,
                datasetNames: [`burstdata:burstdata_Network_Node`]
            });
            var that = this;
            new L.supermap.FeatureService(this.restDataUrl).getFeaturesBySQL(sqlParam, serviceResult => {
                new L.geoJSON(serviceResult.result.features, {
                    onEachFeature: function (feature, layer) {
                        new L.circleMarker(layer.getLatLng(), {
                            radius: 8,
                            weight: 1,
                            fillColor: 'SteelBlue',
                            fillOpacity: 0.5,
                            labelStyle: {
                                text: '阀门',
                                offsetX: -28,
                                font: '18px 微软雅黑 Arial sans-serif',
                                fillStyle: "#6093c5",
                                strokeStyle: "#6093c5"
                            }
                        }).addTo(that.map);
                    }
                });
            });

            this.map.on('click', e => {
                if (this.burstPoint !== undefined) {
                    this.burstPoint.remove();
                    this.burstPoint = undefined;
                }

                if (this.burstPipeline !== undefined) {
                    this.burstPipeline.remove();
                    this.burstPipeline = undefined;
                }

                if (this.criticalPoints.length > 0) {
                    for (let i = 0; i < this.criticalPoints.length; i++) {
                        const criticalPoint = this.criticalPoints[i];
                        criticalPoint.remove();
                    }
                    this.criticalPoints = [];
                }

                this.selectBurstPoint(e.latlng.lat, e.latlng.lng);
            });
        }).catch(err => {
            ElMessage.error(err.stack)
        });
    },
    methods: {
        // 设置爆管点
        selectBurstPoint(lat, lng) {
            var geoJSON = new L.marker([lat, lng]).toGeoJSON();

            var queryParam = new L.supermap.FilterParameter({ name: 'burstdata_Network@burstdata' });

            var queryByGeometryParameters = new L.supermap.QueryByDistanceParameters({
                queryParams: [queryParam],
                isNearest: true,
                expectCount: 1,
                geometry: geoJSON,
                distance: 10
            });

            var queryService = new L.supermap.QueryService(this.restMapUrl, {
                format: 'GEOJSON',
                crossOrigin: true
            });

            var that = this;
            queryService.queryByDistance(queryByGeometryParameters, res => {
                if (res.result.recordsets.length === 0) {
                    ElMessage.warning('当前点击位置附近无管线，请重新选择爆管点');
                } else {
                    var feature = res.result.recordsets[0].features.features[0];
                    var coordinates = feature.geometry.coordinates;
                    that.burstPoint = new L.circleMarker([(coordinates[0][1] + coordinates[1][1]) / 2, (coordinates[0][0] + coordinates[1][0]) / 2], {
                        radius: 9,
                        weight: 1,
                        color: 'red',
                        fillColor: 'red',
                        fillOpacity: 0.3
                    }).bindTooltip('爆管点').addTo(that.map);
                    that.burstPoint.title = feature.properties.SmID;

                    that.burstPipelineAnalyst();
                }
            });
        },

        // 爆管最近阀门查找
        burstPipelineAnalyst() {
            if (this.burstPoint === undefined) {
                ElMessage.warning('当前暂无爆管点！请先设置爆管点后再进行爆管分析');
            } else {
                // 爆管分析
                var that = this;
                var burstPipelineAnalystParameters = new L.supermap.BurstPipelineAnalystParameters({
                    sourceNodeIDs: this.sourceNodeIDs,
                    edgeID: parseInt(this.burstPoint.title),
                    isUncertainDirectionValid: true
                });
                new L.supermap.NetworkAnalystService(that.networkAnalystUrl).burstPipelineAnalyst(burstPipelineAnalystParameters, analystResult => {
                    var edges = analystResult.result.edges;
                    var criticalNodes = analystResult.result.criticalNodes;
                    if (edges !== undefined && edges.length > 0 && criticalNodes !== undefined && criticalNodes.length > 0) {
                        that.highlightBurstPipeline(analystResult.result.edges);
                        that.highlightCriticalPoints(analystResult.result.criticalNodes);
                        ElMessage.success('爆管分析成功，已高亮爆管关键阀门位置');
                    } else {
                        ElMessage.warning('爆管分析失败！未查询到关键阀门位置');
                    }
                });
            }
        },

        // 高亮爆管管线
        highlightBurstPipeline(edges) {
            var that = this;
            var sqlParam = new L.supermap.GetFeaturesBySQLParameters({
                queryParameter: {
                    name: `burstdata_Network@burstdata`,
                    attributeFilter: `SmID in ('${edges.join('\',\'')}')`
                },
                toIndex: -1,
                maxFeatures: edges.length,
                datasetNames: [`burstdata:burstdata_Network`]
            });
            new L.supermap.FeatureService(this.restDataUrl).getFeaturesBySQL(sqlParam, serviceResult => {
                that.burstPipeline = new L.geoJSON(serviceResult.result.features, {
                    style: function () {
                        return {
                            color: 'rgba(255, 0, 0, 0.3)',
                            weight: 4
                        }
                    }
                }).addTo(that.map);
            });
        },

        // 高亮爆管点关键阀门
        highlightCriticalPoints(criticalNodes) {
            var that = this;
            var sqlParam = new L.supermap.GetFeaturesBySQLParameters({
                queryParameter: {
                    name: `burstdata_Network_Node@burstdata`,
                    attributeFilter: `SmID in ('${criticalNodes.join('\',\'')}')`
                },
                toIndex: -1,
                maxFeatures: criticalNodes.length,
                datasetNames: [`burstdata:burstdata_Network_Node`]
            });
            new L.supermap.FeatureService(this.restDataUrl).getFeaturesBySQL(sqlParam, serviceResult => {
                new L.geoJSON(serviceResult.result.features, {
                    onEachFeature: function (feature, layer) {
                        that.criticalPoints[that.criticalPoints.length] = new L.circleMarker(layer.getLatLng(), {
                            radius: 9,
                            weight: 1,
                            color: 'Yellow',
                            fillColor: 'Yellow',
                            fillOpacity: 0.5
                        }).bindTooltip('关键阀门').addTo(that.map);
                    }
                });
            });
        }
    }
}
</script>

<style scoped></style>